package com.jk.eyedemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import com.jk.eyedemo.base.BaseActivity
import com.jk.eyedemo.base.BaseFragment
import com.jk.eyedemo.base.currentFragment
import com.jk.eyedemo.base.tabsId
import com.jk.eyedemo.fragment.CategoryFragment
import com.jk.eyedemo.fragment.HomeFragment
import com.jk.eyedemo.fragment.HotFragment
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setRadio()
    }

    private fun setRadio() {
        rb_home.isChecked = true
        chooseFragment(R.id.rb_home)
        rg_root.setOnCheckedChangeListener { _, checkedId -> chooseFragment(checkedId) }
        //这里的_:如果在lambda中不需要用到的参数可以用_表示
    }

    private fun chooseFragment(checkedId: Int) {
        currentFragment = checkedId
        val beginTransaction = supportFragmentManager.beginTransaction()
        val fragment: Fragment? = supportFragmentManager.findFragmentByTag(checkedId.toString())
        if (fragment == null) {
            when (checkedId) {//这里的when可以理解为switch
                R.id.rb_home -> beginTransaction.add(R.id.fl_content, HomeFragment(), checkedId.toString())
                R.id.rb_hot -> beginTransaction.add(R.id.fl_content, HotFragment(), checkedId.toString())
                R.id.rb_category -> beginTransaction.add(R.id.fl_content, CategoryFragment(), checkedId.toString())
            }
        }

        tabsId.forEach { tab ->
            val aFragment = supportFragmentManager.findFragmentByTag(tab.toString()) as BaseFragment?
            Log.d("MainActivity", tab.toString())
            if (tab == checkedId) {
                aFragment?.let {
                    aFragment.setupToolbar()
                    beginTransaction.show(it)//let可以表示为一个代码块,let中的最后一行代码表示返回值
                }
            } else {
                aFragment?.let {
                    beginTransaction.hide(it)
                }
            }

        }
        beginTransaction.commit()

    }
}
//
//fun main(args: Array<String>) {
//    var a: String? = ""
//    var b = a?.let {
////        println("女海盗")
//        "圣枪游侠"
//    }
//    println(b)
//}


